from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import enum
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin

db = SQLAlchemy()

class ApplicationStatus(enum.Enum):
    PENDING = '待审核'
    APPROVED = '已批准'
    REJECTED = '已拒绝'

class UserType(enum.Enum):
    STUDENT = '学生'
    SUPERVISOR = '导师'

class Application(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    supervisor_name = db.Column(db.String(100), nullable=False)
    password = db.Column(db.String(128), nullable=False)
    username = db.Column(db.String(80), unique=True, nullable=False)
    status = db.Column(db.Enum(ApplicationStatus), default=ApplicationStatus.PENDING)
    submitted_at = db.Column(db.DateTime, default=datetime.utcnow)
    user_type = db.Column(db.Enum(UserType), default=UserType.STUDENT)
    
    # 学生特有字段
    student_id = db.Column(db.String(20), nullable=True)  # 学号
    supervisor_email = db.Column(db.String(120), nullable=True)  # 导师邮箱
    supervisor_approved = db.Column(db.Boolean, default=False)  # 导师是否已审批
    
    # 导师特有字段
    department = db.Column(db.String(100), nullable=True)  # 院系
    research_area = db.Column(db.String(200), nullable=True)  # 研究方向

class Supervisor(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(128))
    department = db.Column(db.String(100), nullable=True)
    research_area = db.Column(db.String(200), nullable=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 作业统计设置
    receive_monthly_report = db.Column(db.Boolean, default=False)
    receive_quarterly_report = db.Column(db.Boolean, default=False)
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

class AdminUser(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(128))

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)